package com.mofofa.maozy.network

import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import com.mofofa.maozy.base.BaseViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlin.Exception
import kotlin.coroutines.CoroutineContext

open class ApiBaseReposity {

    fun showMaozyLoading(caller: ViewModel?) {
        caller?.let {
            if (it is BaseViewModel)
                it.showMaozyLoading()
        }
    }

    fun dismissMaozyLoading(caller: ViewModel?) {
        caller?.let {
            if (it is BaseViewModel)
                it.dismissMaozyLoading()
        }
    }

    fun handleMaozyNetworkMaozyException(caller: ViewModel?, networkException: NetworkException) {
        caller?.let {
            if (it is BaseViewModel)
                it.handleMaozyNetworkMaozyException(networkException)
        }
    }

    fun <T> fire(
        context: CoroutineContext,
        caller: ViewModel? = null,
        showLoading: Boolean = true,
        block: suspend () -> Result<T>,
    ) =
        liveData<Result<T>>(context) {
            //显示loading
            if (showLoading) {
                withContext(Dispatchers.Main) {
                    showMaozyLoading(caller)
                }
            }

            //处理事务
            val result = try {
                block()
            } catch (e: Exception) {
                Result.failure(NetworkException("7777", "Request Error!"))
            }

            //关闭loading
            if (showLoading) {
                withContext(Dispatchers.Main) {
                    dismissMaozyLoading(caller)
                }
            }

            //处理异常
            if (result.isFailure) {
                val throwable = result.exceptionOrNull()
                throwable?.let {
                    if (it is NetworkException) {
                        withContext(Dispatchers.Main) {
                            handleMaozyNetworkMaozyException(caller, it)
                        }
                    } else {
//                        withContext(Dispatchers.Main) {
//                            Toast.makeText(
//                                MyApplication.context,
//                                "result is falure",
//                                Toast.LENGTH_SHORT
//                            )
//                                .show()
//                        }
                    }
                }
            }
            emit(result)
        }
}